<template>
  <div class="dashboard">
    <a-row :gutter="[16, 16]">
      <!-- 统计卡片 -->
      <a-col :xs="24" :sm="12" :lg="6" v-for="stat in statistics" :key="stat.title">
        <a-card class="stat-card" :class="stat.color">
          <div class="stat-content">
            <div class="stat-icon">
              <component :is="stat.icon" />
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[16, 16]" style="margin-top: 16px;">
      <!-- 最近工单 -->
      <a-col :xs="24" :lg="16">
        <a-card title="最近工单" :bordered="false">
          <template #extra>
            <a-button type="link" @click="router.push('/workorder/list')">
              查看全部
            </a-button>
          </template>

          <a-table
            :columns="workOrderColumns"
            :data-source="recentWorkOrders"
            :pagination="false"
            size="small"
            :scroll="{ x: 600, y: 1200}"
            :loading="loading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-button
                  type="link"
                  size="small"
                  @click="router.push(`/workorder/detail/${record.id}`)"
                >
                  查看
                </a-button>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 快捷操作 -->
      <a-col :xs="24" :lg="8">
        <a-card title="快捷操作" :bordered="false">
          <div class="quick-actions">
            <a-button
              v-if="userStore.isStudent"
              type="primary"
              block
              size="large"
              :icon="h(PlusOutlined)"
              @click="router.push('/workorder/create')"
              style="margin-bottom: 12px;"
            >
              创建工单
            </a-button>

            <a-button
              block
              size="large"
              :icon="h(BellOutlined)"
              @click="router.push('/notification')"
              style="margin-bottom: 12px;"
            >
              通知中心
              <a-badge :count="unreadCount" :offset="[10, 0]" />
            </a-button>

            <a-button
              block
              size="large"
              :icon="h(UserOutlined)"
              @click="router.push('/profile')"
            >
              个人中心
            </a-button>
          </div>
        </a-card>

        <!-- 库存预警（维修工和管理员可见） -->
        <a-card
          v-if="userStore.isRepairWorker || userStore.isAdmin"
          title="库存预警"
          :bordered="false"
          style="margin-top: 16px;"
        >
          <template #extra>
            <a-button type="link" @click="router.push('/material/list')">
              查看全部
            </a-button>
          </template>

          <a-list
            :data-source="warningMaterials"
            :loading="loading"
            size="small"
            :style="{ maxHeight: '350px', overflowY: 'auto' }"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    <span>{{ item.name }}</span>
                    <a-tag color="orange" size="small" style="margin-left: 8px;">
                      库存: {{ item.stockCount }}
                    </a-tag>
                  </template>
                  <template #description>
                    预警值: {{ item.warningThreshold }}
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, h, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getWorkOrderList, getWorkOrderStats } from '@/api/workorder'
import { getWarningMaterials } from '@/api/material'
import { getUnreadCount } from '@/api/notification'
import { WorkOrderStatus } from '@/types'
import type { WorkOrder, Material, WorkOrderStatsResponse } from '@/types'
import {
  ToolOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  StarOutlined,
  PlusOutlined,
  BellOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const recentWorkOrders = ref<WorkOrder[]>([])
const warningMaterials = ref<Material[]>([])
const unreadCount = ref(0)
const workOrderStats = ref<WorkOrderStatsResponse>({
  totalCount: 0,
  pendingCount: 0,
  completedCount: 0,
  reviewedCount: 0,
  cancelledCount: 0,
  inProgressCount: 0
})

// 统计数据
const statistics = computed(() => {
  // 如果是学生，显示个人工单统计（基于最近工单列表）
  if (userStore.isStudent) {
    return [
      {
        title: '我的工单',
        value: recentWorkOrders.value.length,
        icon: h(ToolOutlined),
        color: 'blue'
      },
      {
        title: '待处理',
        value: recentWorkOrders.value.filter(item => item.status === WorkOrderStatus.PENDING).length,
        icon: h(ClockCircleOutlined),
        color: 'orange'
      },
      {
        title: '已完成',
        value: recentWorkOrders.value.filter(item => item.status === WorkOrderStatus.COMPLETED).length,
        icon: h(CheckCircleOutlined),
        color: 'green'
      },
      {
        title: '已评价',
        value: recentWorkOrders.value.filter(item => item.status === WorkOrderStatus.REVIEWED).length,
        icon: h(StarOutlined),
        color: 'purple'
      }
    ]
  }

  // 管理员和维修工显示全局统计数据
  return [
    {
      title: '总工单',
      value: workOrderStats.value.totalCount,
      icon: h(ToolOutlined),
      color: 'blue'
    },
    {
      title: '待处理',
      value: workOrderStats.value.pendingCount,
      icon: h(ClockCircleOutlined),
      color: 'orange'
    },
    {
      title: '已完成',
      value: workOrderStats.value.completedCount,
      icon: h(CheckCircleOutlined),
      color: 'green'
    },
    {
      title: '已评价',
      value: workOrderStats.value.reviewedCount,
      icon: h(StarOutlined),
      color: 'purple'
    }
  ]
})

// 工单表格列配置
const workOrderColumns = [
  {
    title: '工单编号',
    dataIndex: 'workOrderId',
    key: 'workOrderId',
    width: 150
  },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120,
    customRender: ({ text }: { text: string }) => {
      return new Date(text).toLocaleDateString()
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 80
  }
]

// 获取状态颜色
const getStatusColor = (status: WorkOrderStatus) => {
  const colorMap = {
    [WorkOrderStatus.PENDING]: 'orange',
    [WorkOrderStatus.IN_PROGRESS]: 'blue',
    [WorkOrderStatus.COMPLETED]: 'green',
    [WorkOrderStatus.REVIEWED]: 'purple',
    [WorkOrderStatus.CANCELLED]: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: WorkOrderStatus) => {
  const textMap = {
    [WorkOrderStatus.PENDING]: '待处理',
    [WorkOrderStatus.IN_PROGRESS]: '处理中',
    [WorkOrderStatus.COMPLETED]: '已完成',
    [WorkOrderStatus.REVIEWED]: '已评价',
    [WorkOrderStatus.CANCELLED]: '已取消'
  }
  return textMap[status] || '未知'
}

// 获取最近工单
const fetchRecentWorkOrders = async () => {
  try {
    loading.value = true
    const queryParams: Record<string, unknown> = {
      pageSize: 10,
      lastId: 0
    }

    // 学生只能看自己的工单
    if (userStore.isStudent) {
      queryParams.reporterId = userStore.userInfo?.id
    }

    const response = await getWorkOrderList(queryParams)
    if (response.code === 0) {
      recentWorkOrders.value = response.data?.records || []
    }
  } catch (error) {
    console.error('获取工单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取库存预警物料
const fetchWarningMaterials = async () => {
  if (!userStore.isRepairWorker && !userStore.isAdmin) return

  try {
    const response = await getWarningMaterials()
    if (response.code === 0) {
      warningMaterials.value = response.data || []
    }
  } catch (error) {
    console.error('获取库存预警失败:', error)
  }
}

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    const response = await getUnreadCount()
    if (response.code === 0) {
      unreadCount.value = response.data
    }
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

// 获取工单统计数据（仅管理员和维修工）
const fetchWorkOrderStats = async () => {
  if (userStore.isStudent) return

  try {
    const response = await getWorkOrderStats()
    if (response.code === 0) {
      workOrderStats.value = response.data
    }
  } catch (error) {
    console.error('获取工单统计失败:', error)
  }
}

onMounted(() => {
  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' }
  ])

  // 获取数据
  fetchRecentWorkOrders()
  fetchWarningMaterials()
  fetchUnreadCount()
  fetchWorkOrderStats()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stat-card {
  border-radius: 8px;
  overflow: hidden;
}

.stat-card.blue {
  border-left: 4px solid #1890ff;
}

.stat-card.orange {
  border-left: 4px solid #fa8c16;
}

.stat-card.green {
  border-left: 4px solid #52c41a;
}

.stat-card.purple {
  border-left: 4px solid #722ed1;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 32px;
  margin-right: 16px;
  opacity: 0.8;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.quick-actions {
  display: flex;
  flex-direction: column;
}
</style>
